package com.javajun.endofterm.service;

import com.javajun.endofterm.common.CommonService;
import com.javajun.endofterm.entity.Student;
import com.javajun.endofterm.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Xiong Limin
 * Date: 2020-11-30-11:56 下午
 */
@Service
public class StudentService extends CommonService<Student, Integer> {

    @Autowired
    private StudentRepository studentRepository;

    public Student findByUsername(String username) {
        return studentRepository.findByUsername(username);
    }

    /**
     * 获取当前登录学生的宿舍的剩余电量
     * @return
     */
    public Double getLoadStudentDomitoryPower() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        Student student = studentRepository.findByUsername(username);
        return student.getDomitory().getSurplusPower();
    }

    /**
     * 获取当前登录学生用户的宿舍 ID
     * @return
     */
    public int getLodStudentDomitoryId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        Student student = studentRepository.findByUsername(username);
        return student.getDomitory().getId();
    }


    /**
     * 判断当前登录用户是否是学生用户
     * @return
     */
    public boolean whetherStudent() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Set<String> rolSet = AuthorityUtils.authorityListToSet(auth.getAuthorities());
        return rolSet.contains("ROLE_STUDENT");
    }

}
